<template>
  <section class="content">
    <div class="header">
      <div class="titleSty">创建合同</div>
      <div>
        <template v-for="(item, index) in buttonList">
          <el-button :key="index"
                     type="primary"
                     :plain="item.type!=3"
                     :loading="loading"
                     @click="submit(item.type)">{{item.label}}</el-button>
        </template>
      </div>
    </div>
    <el-form ref="ruleForm"
             :model="form"
             label-width="110px"
             label-position="right"
             size="small"
             :rules="rules">
      <el-row :gutter="28"
              class="mt20">
        <el-col :span="7">
          <el-form-item label="合同编号"
                        prop="contractNo"
                        :rules="[
                {
                  required: true,
                  message: `请输入合同编号，只可输入数字、字母和特殊符号(-_()&+/[])`,
                  validator: validatePactCode,
                  trigger: 'blur'
                }
              ]">
            <el-input v-model="form.contractNo"
                      placeholder="请输入合同编号"
                      maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="合同名称"
                        prop="contractName"
                        :rules="[
                {
                  required: true,
                  message: `请输入合同名称，只可输入数字、字母和汉字`,
                  validator: validateText,
                  trigger: 'blur'
                }
              ]">
            <el-input v-model="form.contractName"
                      placeholder="请输入合同名称"
                      maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="合同有效期"
                        prop="contractDate">
            <el-date-picker v-model="form.contractDate"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions"
                            @blur="changeTime(form.contractDate)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20"
              class="mt10">
        <el-form-item label="合同内容"
                      prop="contentBody">
          <EditorContract :content-body.sync="form.contentBody" />
        </el-form-item>
      </el-row>
      <el-row :gutter="20"
              class="mt10">
        <el-form-item label="附件"
                      prop="contractAttachments">
          <upload-file-selector :is-onload="true"
                                :is-contract="true"
                                :is-cover="true"
                                :text="text"
                                :file-size="10"
                                :request-url="requestUrl"
                                :attach-form.sync="form.contractAttachments"
                                @handleUpload="handleUpload" />
        </el-form-item>
      </el-row>
      <el-row :gutter="20"
              class="mt20">
        <el-col :span="3">
          <el-form-item label="签署双方"
                        :rules="[
                  {
                    required: true,
                    message: `请输入`
                  }
                ]"></el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="甲方"
                        prop="tenantNameOne">
            <el-input v-model="form.tenantNameOne"
                      placeholder="请点击选择"
                      :disabled="contractType === 2"
                      @focus="cstVisible = true" />
          </el-form-item>
          <el-form-item label="甲方代表人"
                        prop="sealUserNameOne"
                        :rules="[
                {
                  required: true,
                  message: `请输入甲方代表人，只可输入数字、字母和汉字`,
                  validator: validateText,
                  trigger: 'blur'
                }
              ]">
            <el-input v-model="form.sealUserNameOne"
                      placeholder="请输入甲方代表人"
                      maxlength="10" />
          </el-form-item>
        </el-col>
        <el-col :span="7"
                class="ml290">
          <el-form-item label="乙方"
                        prop="tenantNameTwo">
            <el-input v-model="form.tenantNameTwo"
                      placeholder="请点击选择"
                      :disabled="contractType === 1"
                      @focus="visible = true" />
          </el-form-item>
          <el-form-item label="乙方代表人"
                        prop="sealUserNameTwo"
                        :rules="[
                {
                  required: true,
                  message: `请输入乙方代表人，只可输入数字、字母和汉字`,
                  validator: validateText,
                  trigger: 'blur'
                }
              ]">
            <el-input v-model="form.sealUserNameTwo"
                      placeholder="请输入乙方代表人"
                      maxlength="10" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <select-cst v-if="cstVisible"
                :cst-visible.sync="cstVisible"
                @selectCst="selectCst" />
    <select-carrier v-if="visible"
                    :visible.sync="visible"
                    @selectCarrier="selectCarrier" />
  </section>
</template>
<script>
import EditorContract from "./components/EditorContract.vue";
import UploadFileSelector from "@/components/advance/upload/UploadFileSelector.vue";
import SelectCarrier from "./components/SelectCarrier.vue";
import SelectCst from "./components/SelectCst.vue";
import { contract, seal, tenant } from "@/api/index.js";
import _ from 'lodash'
let formInfo;
let timeOptionRange;

export default {
  name: "CreateContract",
  components: {
    EditorContract,
    UploadFileSelector,
    SelectCarrier,
    SelectCst
  },
  data () {
    return {
      loading: false,
      cstVisible: false,
      visible: false,
      rules: {
        contractNo: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
        contractName: [{ required: true, message: "请输入合同名称", trigger: "blur" }],
        contractDate: [{ required: true, message: "请选择合同有效期", trigger: "blur" }],
        contentBody: [{ required: true, message: "请输入合同内容", trigger: "blur" }],
        tenantNameOne: [{ required: true, message: "请选择甲方", trigger: "change" }],
        sealUserNameOne: [{ required: true, message: "请输入甲方代表人", trigger: "change" }],
        tenantNameTwo: [{ required: true, message: "请选择乙方", trigger: "change" }],
        sealUserNameTwo: [{ required: true, message: "请输入乙方代表人", trigger: "change" }],
      },
      form: {
        contractNo: null,  // 合同信息
        contractName: null,
        contentBody: null,
        contractDate: null, //有效期
        effectiveDate: "",
        expireDate: "",
        tenantIdOne: null,  // 甲方
        tenantNameOne: null,
        sealUserNameOne: null,
        tenantIdTwo: null,  // 乙方
        tenantNameTwo: null,
        sealUserNameTwo: null,
        contractAttachments: [], // 附件
        contractType: null
      },
      buttonList: [
        { label: "返回", type: 0 },
        { label: "保存", type: 1 },
        { label: "预览", type: 2 },
        { label: "签署", type: 3 }
      ],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {

          if (minDate && !maxDate) {
            timeOptionRange = minDate
          }
          if (maxDate) {
            timeOptionRange = null
          }
        },
        disabledDate (time) {
          console.log("===", timeOptionRange)
          // 设置1天的时间戳
          let intervalTime = 1 * 24 * 60 * 60 * 1000
          if (timeOptionRange)
            return time.getTime() < timeOptionRange.getTime() + intervalTime
        }
      },
      requestUrl: `/cert/cert/upload/1`,
      fileSize: 10
    };
  },
  computed: {
    contractType () {  //1：发货方合同 2：承运方合同 
      const { name } = this.$route
      return this.form?.contractType || (name === 'createCarrierContract' ? 2 : 1)
    },
    contractId () {
      return this.$route.query?.contractId
    },
    text () {
      return `附件支持doc(docx)、xls(xlsx)、pdf、txt、jpg、png、zip、rar，单个文件不能大于${this.fileSize}MB`
    }
  },
  beforeRouteEnter (to, from, next) {
    if (from.name === "contractPreview") {
      formInfo = { ...from.params }
    }
    next();
  },
  created () {
    if (formInfo) {
      this.form = { ...formInfo };
    } else {
      if (this.contractId) this.getDetails();
      this.getTenantInfo();
    }
  },
  methods: {
    // 合同编号输入校验
    validatePactCode (rule, value, callback) {
      if (value) {
        if (
          value &&
          value.match(/^[a-zA-Z0-9\-\_\(\)\&\+\/\[\]]{0,30}$/) == null
        ) {
          callback(
            new Error("只可输入数字、字母和特殊符号(-_()&+/[])")
          );
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入合同编号"));
      }
    },
    // 合同名称、甲乙代表人名称效验
    validateText (rule, value, callback) {
      if (value) {
        if (
          value &&
          value.match(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/) == null
        ) {
          callback(
            new Error("只可输入数字、字母和汉字")
          );
        } else {
          callback();
        }
      } else {
        callback(new Error("只可输入数字、字母和汉字"));
      }
    },
    // 获取当前租户信息
    async getTenantInfo () {
      let { data } = await tenant.getTenantInfo(this.contractId);
      if (this.contractType === 2) {
        this.form.tenantIdOne = data.tenantId;
        this.form.tenantNameOne = data.name;
        this.form.sealUserNameOne = data.company.contactName;
      } else {
        this.form.tenantIdTwo = data.tenantId;
        this.form.tenantNameTwo = data.name;
        this.form.sealUserNameTwo = data.company.contactName;
      }
    },
    // 获取详情
    async getDetails () {
      let { data } = await contract.getDetail(this.contractId);
      this.form = { ...data };
      this.form.contractDate = [data.effectiveDate, data.expireDate];
    },
    //客户
    selectCst (cst) {
      this.form.tenantIdOne = cst.relation.upstream;
      this.form.tenantNameOne = cst.name;
      this.form.sealUserNameOne = cst.contactName;
      this.checkSeal()
    },
    //承运方
    selectCarrier (carrier) {
      this.form.tenantIdTwo = carrier.relation.downstream;
      this.form.tenantNameTwo = carrier.name;
      this.form.sealUserNameTwo = carrier.contactName;
      this.checkSeal()
    },
    changeTime (val) {
      this.form.contractDate = [this.$moment(val[0]).format("YYYY-MM-DD"), this.$moment(val[1]).format("YYYY-MM-DD")];
      this.form.effectiveDate = this.$moment(val[0]).format("YYYY-MM-DD");
      this.form.expireDate = this.$moment(val[1]).format("YYYY-MM-DD");
      this.$forceUpdate()
    },
    // 上传附件
    handleUpload (fileList) {
      console.log("======><", fileList)
      this.form.contractAttachments = fileList;
    },
    // 校验双方公司是否开通印章功能
    async checkSeal () {
      let { data } = await seal.checkSeal(this.form.tenantIdOne, this.form.tenantIdTwo);
      if (data) this.$message.success("双方都已开通电子印章服务")
    },
    // 触发事件
    submit: _.debounce(function (val) {    // 触发事件
      if (val === 0) {
        this.back()
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (val === 1) {
              if (this.contractId) {
                this.update()
              } else {
                this.create(1)
              }
            }
            else if (val === 2) this.preview();
            else this.sign()
          }
        });
      }
    }, 600),
    getParams () {
      let attachments = []
      if (this.form.contractAttachments.length) {
        attachments = this.form.contractAttachments.map((x) => {
          return {
            name: x.attachName,
            url: x.attachUrl,
            id: x.id
          };
        });
      }
      let params = {
        ...this.form,
        contractType: this.contractType,
        contractAttachments: attachments
      }
      return params
    },
    // 创建合同
    async create (contractStatus) {
      this.loading = true;
      let params = this.getParams()
      let { data, code } = await contract.createContract({ ...params, contractStatus })
        .catch(() => {
          this.loading = false;
        });
      if (code === 0) {
        this.loading = false;
        if (contractStatus === 1) {
          this.$message.success("已保存到草稿")
          this.back()
        } else {
          this.goContractDetail(data)
        }
      }
    },
    // 修改合同
    async update (type) {
      this.loading = true;
      let params = this.getParams()
      let { code } = await contract.updateContract({ ...params, contractId: this.contractId, contractStatus: 1 })
        .catch(() => {
          this.loading = false;
        });
      if (code === 0) {
        this.loading = false;
        if (type) {
          this.sendContract()
        } else {
          this.back()
        }
      }
    },
    //预览
    preview () {
      let formParams = this.getParams()
      this.$router.push({
        name: "contractPreview",
        query: {
          isPreview: 1
        },
        params: {
          ...formParams,
          contractId: this.contractId
        }
      });
    },
    // 发起
    sign () {
      this.$confirm("确认是否签署合同", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (this.contractId) {
          this.update('sign')
        } else {
          this.create(2)
        }
      });
    },
    // 发起
    async sendContract () {
      let { data } = await contract.sendContract({ contractId: this.contractId })
      this.goContractDetail(data)
    },
    // 发起后跳转
    goContractDetail (data) {
      let query = data.includes('//') ? { pdfUrl: data } : { contractId: data, isSended: 1 }
      this.$router.push({
        name: "contractPreview",
        query
      });
    },
    // 返回
    back () {
      this.$router.back();
    },
  },
  beforeDestroy () {
    formInfo = null
  }
};
</script>
<style lang="scss" scoped>
.content {
  background: var(--prev-bg-white);
  padding: 20px;
  position: relative;
  height: 88vh;
  overflow-y: auto;
}
.body {
  height: 80vh;
  overflow-x: hidden;
}
.titleSty {
  width: 200px;
  height: 16px;
  border-left: 2px solid var(--prev-color-primary);
  padding-left: 6px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: 500;
}
.mt10 {
  margin-top: 10px;
}
.mt20 {
  margin-top: 20px;
}
.ml290 {
  margin-left: 290px;
}
.header {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
</style>
